package com.sxhuayuan.parking.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.sxhuayuan.parking.dao.BaseDao;
import com.sxhuayuan.parking.dao.MemberCarPlateDao;
import com.sxhuayuan.parking.entity.Member;
import com.sxhuayuan.parking.entity.MemberCarPlate;
import com.sxhuayuan.parking.service.MemberCarPlateService;

@Service("memberCarPlateServiceImpl")
public class MemberCarPlateServiceImpl extends BaseServiceImpl<MemberCarPlate, Long> implements MemberCarPlateService {

	@Autowired
	MemberCarPlateDao dao;

	@Override
	public BaseDao<MemberCarPlate, Long> getDAO() {

		return dao;
	}

	@Override
	public List<MemberCarPlate> findList(Long memberId) {
		return dao.findByMemberList(memberId);
	}

	@Override
	public MemberCarPlate findByMemberIdAndCarPlate(Long memberId, String carPlate) {
		return dao.findByMemberIdAndCarPlate(memberId, carPlate);
	}

	@Override
	public Long findCount(Long memberId) {
		return dao.count(new Specification<MemberCarPlate>() {
			@Override
			public Predicate toPredicate(Root<MemberCarPlate> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				return criteriaBuilder.equal(root.get("member").get("id"), memberId);
			}
		});
	}

	@Override
	public void setDefault(Member member, Long carPlateId) {
		for (MemberCarPlate cp : member.getCarPlates()) {
			cp.setIsDef(cp.getId().longValue() == carPlateId.longValue());
		}
	}

	@Override
	public void saveIfNotBind(Member member, String carPlate, Boolean isDef) {
		MemberCarPlate entity = findByMemberIdAndCarPlate(member.getId(), carPlate);
		if (entity == null) {
			if (isDef) {
				dao.cancelAllCarPlateDef(member.getId());
			}
			entity = new MemberCarPlate();
			entity.setMember(member);
			entity.setCarPlate(carPlate);
			entity.setIsDef(isDef);
			save(entity);
		}
	}
}
